package org.mall.modules.cash.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.mall.common.api.vo.Result;
import org.mall.common.api.vo.UserInfo;
import org.mall.common.aspect.annotation.AutoLog;
import org.mall.common.constant.SellerCashStatusEnum;
import org.mall.common.system.query.QueryGenerator;
import org.mall.common.system.util.JwtUtil;
import org.mall.common.util.oConvertUtils;
import org.mall.modules.cash.entity.SellerCashInfo;
import org.mall.modules.cash.entity.SellerCashInfoVO;
import org.mall.modules.cash.service.ISellerCashInfoService;
import org.mall.modules.pojo.seller.SellerDTO;
import org.mall.modules.pojo.shop.ShopDTO;
import org.mall.modules.seller.entity.Seller;
import org.mall.modules.seller.entity.SellerVo;
import org.mall.modules.seller.service.ISellerService;
import org.mall.modules.shop.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

 /**
 * @Description: 提现信息表
 * @Author: jeecg-boot
 * @Date:   2019-12-31
 * @Version: V1.0
 */
@Slf4j
@Api(tags="提现信息表")
@RestController
@RequestMapping("/cashInfoLog")
public class SellerCashInfoController {
	@Autowired
	private ISellerCashInfoService sellerCashInfoService;

	 @Autowired
	 private IShopService shopService;
	 @Autowired
	 private ISellerService sellerService;
	
	/**
	  * 分页列表查询
	 * @param sellerCashInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "提现信息表-分页列表查询")
	@ApiOperation(value="提现信息表-分页列表查询", notes="提现信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<SellerCashInfo>> queryPageList(SellerCashInfo sellerCashInfo,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<SellerCashInfo>> result = new Result<IPage<SellerCashInfo>>();
		QueryWrapper<SellerCashInfo> queryWrapper = QueryGenerator.initQueryWrapper(sellerCashInfo, req.getParameterMap());
		Page<SellerCashInfo> page = new Page<SellerCashInfo>(pageNo, pageSize);
		IPage<SellerCashInfo> pageList = sellerCashInfoService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param sellerCashInfo
	 * @return
	 */
	@AutoLog(value = "提现信息表-添加")
	@ApiOperation(value="提现信息表-添加", notes="提现信息表-添加")
	@PostMapping(value = "/add")
	public Result<SellerCashInfo> add(@RequestBody SellerCashInfo sellerCashInfo) {
		Result<SellerCashInfo> result = new Result<SellerCashInfo>();
		try {
			sellerCashInfoService.save(sellerCashInfo);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param sellerCashInfo
	 * @return
	 */
	@AutoLog(value = "提现信息表-编辑")
	@ApiOperation(value="提现信息表-编辑", notes="提现信息表-编辑")
	@PutMapping(value = "/edit")
	public Result<SellerCashInfo> edit(@RequestBody SellerCashInfo sellerCashInfo) {
		Result<SellerCashInfo> result = new Result<SellerCashInfo>();
		SellerCashInfo sellerCashInfoEntity = sellerCashInfoService.getById(sellerCashInfo.getId());
		if(sellerCashInfoEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = sellerCashInfoService.updateById(sellerCashInfo);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "提现信息表-通过id删除")
	@ApiOperation(value="提现信息表-通过id删除", notes="提现信息表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			sellerCashInfoService.removeById(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "提现信息表-批量删除")
	@ApiOperation(value="提现信息表-批量删除", notes="提现信息表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<SellerCashInfo> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<SellerCashInfo> result = new Result<SellerCashInfo>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.sellerCashInfoService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "提现信息表-通过id查询")
	@ApiOperation(value="提现信息表-通过id查询", notes="提现信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result queryById(@RequestParam(name="id",required=true) String id) {
		List<SellerCashInfoVO> sellerCashInfoVO = sellerCashInfoService.getBySellerId(id);
		if(sellerCashInfoVO==null) {
			return Result.error("无记录");
		}else {
			sellerCashInfoVO.forEach(sellerCashInfoVO1 -> {
				//计算提现成功的金额
				sellerCashInfoVO1.setCashingMoney(sellerCashInfoVO.stream().filter(o ->{
					if (SellerCashStatusEnum.CASH_ING.getValue().equals(o.getStatus())){
						return true;
					}
					return false;
				}).collect(Collectors.toList()).stream().mapToInt(SellerCashInfoVO::getPresentPrice).sum());

				//计算待提现的金额
				sellerCashInfoVO1.setAvailableCash(sellerCashInfoVO.stream().filter(o ->{
					if (SellerCashStatusEnum.WAIT_CASH.getValue().equals(o.getStatus())
							|| SellerCashStatusEnum.CASH_FAILURE.getValue().equals(o.getStatus())){
						return true;
					}
					return false;
				}).collect(Collectors.toList()).stream().mapToInt(SellerCashInfoVO::getPresentPrice).sum());

				//计算提现成功的金额
				sellerCashInfoVO1.setHasCash(sellerCashInfoVO.stream().filter(o ->{
					if (SellerCashStatusEnum.CASH_SUCCESS.getValue().equals(o.getStatus())){
						return true;
					}
					return false;
				}).collect(Collectors.toList()).stream().mapToInt(SellerCashInfoVO::getPresentPrice).sum());
			});
			return Result.ok(sellerCashInfoVO);
		}
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<SellerCashInfo> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              SellerCashInfo sellerCashInfo = JSON.parseObject(deString, SellerCashInfo.class);
              queryWrapper = QueryGenerator.initQueryWrapper(sellerCashInfo, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<SellerCashInfo> pageList = sellerCashInfoService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "提现信息表列表");
      mv.addObject(NormalExcelConstants.CLASS, SellerCashInfo.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("提现信息表列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<SellerCashInfo> listSellerCashInfos = ExcelImportUtil.importExcel(file.getInputStream(), SellerCashInfo.class, params);
              sellerCashInfoService.saveBatch(listSellerCashInfos);
              return Result.ok("文件导入成功！数据行数:" + listSellerCashInfos.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

  @GetMapping("/seller/getSellerCashInfoList")
  public Result getSellerCashInfo(){
	  UserInfo userInfo= JwtUtil.getUserInfoByToken();
	  if (userInfo.getType()==1){
	  	return Result.error("");
	  }
	  List<ShopDTO> list=shopService.getListOfStores(userInfo.getUserId());
	  if (list.isEmpty()){
	  	return Result.ok(Collections.emptyList());
	  }
	  List<String> shopIds=list.stream().map(o->{return o.getId();}).collect(Collectors.toList());
	  List<SellerCashInfo> list1=sellerCashInfoService.getSellerCashInfoLogListByShopIds(shopIds);
	  Map<String,List<SellerCashInfo>> map=list1.stream().collect(Collectors.groupingBy(SellerCashInfo::getShopId));
	  Iterator<String> iterator=map.keySet().iterator();
	  List<JSONObject> jsonObjects=new ArrayList<>();
	  while (iterator.hasNext()){
	  	JSONObject jsonObject=new JSONObject();
	  	String shopId=iterator.next();
	  	jsonObject.put("shopId",shopId);
	  	for (ShopDTO shopDTO:list){
	  		if (shopDTO.getId().equals(shopId)){
				jsonObject.put("shopName",shopDTO.getShopName());
				break;
			}
		}
		  int num1=map.get(shopId).stream().filter(o->{return SellerCashStatusEnum.CASH_ING.getValue()== o.getStatus();}).mapToInt(SellerCashInfo::getPresentPrice).sum();
	  	jsonObject.put("hasCash",num1);
	  	int num2=map.get(shopId).stream().filter(o->{return SellerCashStatusEnum.CASH_ING.getValue()!=o.getStatus();}).mapToInt(SellerCashInfo::getPresentPrice).sum();
	  	jsonObject.put("waitCash",num2);
	  	jsonObjects.add(jsonObject);
	  }
  	return Result.ok(jsonObjects);
  }

	 /**
	  * 管理端查询所有用户待提现金额及已提现金额列表
	  * @return
	  */
  @GetMapping("/merchant/getSellersCashInfo")
  public Result getSellersCashInfo(SellerVo vo,
								   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
								   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize){
	  Page<SellerVo> page = new Page<SellerVo>();
	  vo.setIsDelete(0);
	  vo.setType(0);
  	//获取所有用户信息得到用户Id，用户名称，用户手机号码
  	  List<SellerVo> sellerVoList = sellerService.getSellersFilterIsDeleteAndType(vo,pageNo,pageSize);
	  //计算用户的已提现、可提现、提现中的金额
		sellerVoList.forEach(sellerVo -> {
			//计算用户已提现金额
			sellerVo.setHasCash(sellerVo.getSellerCashInfoList().stream().
				filter(o->{
					if (SellerCashStatusEnum.CASH_SUCCESS.getValue().equals(o.getStatus())){
						return true;
					}
						return false;
				}).collect(Collectors.toList()).stream().mapToInt(SellerCashInfo::getPresentPrice).sum());
			//计算用户可提现金额
			sellerVo.setAvailableCash(sellerVo.getSellerCashInfoList().stream().filter(sellerCashInfo1 -> {
				if (SellerCashStatusEnum.CASH_FAILURE.getValue().equals(sellerCashInfo1.getStatus())
						|| SellerCashStatusEnum.WAIT_CASH.getValue().equals(sellerCashInfo1.getStatus())){
					return true;
				}
				return false;
			}).collect(Collectors.toList()).stream().mapToInt(SellerCashInfo::getPresentPrice).sum());
			//计算用户提现中的金额
			sellerVo.setCashingMoney(sellerVo.getSellerCashInfoList().stream().filter(sellerCashInfo1 -> {
				if (SellerCashStatusEnum.CASH_ING.getValue().equals(sellerCashInfo1.getStatus())){
					return true;
				}
				return false;
			}).collect(Collectors.toList()).stream().mapToInt(SellerCashInfo::getPresentPrice).sum());

		});
	  page.setRecords(sellerVoList);
		return Result.ok(page);
  }

}
